package cn.maxhou.controller;

import cn.maxhou.entity.Supplier;
import cn.maxhou.entity.SysRole;
import cn.maxhou.entity.SysUser;
import cn.maxhou.service.SupplierService;
import cn.maxhou.service.UploadService;
import cn.maxhou.util.Constants;
import cn.maxhou.util.Page;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/supplier")
public class SupplierController extends BaseController {
    private static final Logger LOGGER= LoggerFactory.getLogger(SupplierController.class);

    @Autowired
    private SupplierService supplierService;

    @Autowired
    @Qualifier("toLocalUploadService")
    private UploadService uploadService;

    @ResponseBody
    @GetMapping("/supCodeExist")
    public String accountExist(@RequestParam String supCode) throws Exception {
        LOGGER.debug("检查供应商编号supCode={}的用户是否存在", supCode);
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        if (StringUtils.isEmpty(supCode)) {
            resultMap.put("exist", 0);
        }else {
            try{
                Supplier supplier =supplierService.getSupplierBysupCode(supCode);
                if (supplier != null) {
                    //已经存在,设置1
                    resultMap.put("exist", 1);
                }else {
                    resultMap.put("exist", 0);
                }
            }catch (Exception e){
                LOGGER.error("SysUserController中的accountExist方法执行发生错误", e);
                resultMap.put("error", "出现异常,请联系管理员处理!");
            }
        }
        System.out.println(JSON.toJSONString(resultMap));
        return JSON.toJSONString(resultMap);
    }


    @RequestMapping("/page")
    public String page(Model model, Supplier condition,
                       @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        Page<Supplier> page=null;
        try{
            //查询用户的分页信息
            page=supplierService.findpage(condition,pageNo,pageSize);
            //将分页数据,角色列表和查询条件设置到模型数据中
            model.addAttribute("condition",condition);
            model.addAttribute("pageInfo",page);
        } catch (Exception e) {
            LOGGER.error("SupplierController中的page方法执行发生的错误",e);
            throw new RuntimeException(e);
        }
        return "supplier/page";
    }

    @RequestMapping("/save")
    public String save(Model model){
        //回显数据时需要sysUser,这里给个空对象避免出错
        model.addAttribute("supplier",new Supplier());
        return "supplier/save";
    }

    @PostMapping("/save")
    public String dosave(Supplier supplier, MultipartFile bizPic){
        //允许的上传文件后缀
        String[] allowImageExt={"jpg","jpeg","png","gif","bmp"};
        try{
            if(bizPic!=null){
                //调用上传文件服务,返回上传成功的路径,为null表示没上传
                String bizPicPath = uploadService.uploadFile(bizPic, allowImageExt);
                supplier.setBizPicPath(bizPicPath);
            }
            //通过父类的session方法获取登录用户,由于泛型自动转换无需强转
            SysUser loginUser=session(Constants.SESSION_USER);
            if (supplier.getId()==null){
                supplier.setCreatedUserId(loginUser.getId());
                supplier.setCreatedTime(new Date());
            }else {
                supplier.setUpdatedUserId(loginUser.getId());
                supplier.setUpdatedTime(new Date());
            }
            int ok = supplierService.save(supplier);
            if (ok==1){
                //保存成功,跳回列表页面
                return redirect("/main/supplier/page");
            }
        } catch (Exception e) {
            LOGGER.error("SupplierController中的doSave方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model) throws IOException {
        Supplier supplier=null;
        try{
            supplier =supplierService.getById(id);
            model.addAttribute("supplier",supplier);
        } catch (Exception e) {
            LOGGER.error("SupplierController中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "supplier/view";
    }

    /**查询用户信息并跳转修改页(公用save.jsp)*/
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id")Long id,Model model){
        Supplier supplier=null;
        try{
            supplier =supplierService.getById(id);
            //回显数据时需要sysUser,这里给个空对象避免出错
            model.addAttribute("supplier",supplier);
        } catch (Exception e) {
            LOGGER.error("SupplierController中的toEdit方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    @GetMapping("/del/{id}")
    @ResponseBody
    public Map del(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        HashMap resultMap=new HashMap<String,Object>();
        int flag=0;
        try{
            flag =supplierService.deleteById(id);

            if (flag>0){
                resultMap.put("code",200);
                System.out.println("删除成功");
            }else {
                resultMap.put("code",500);
                resultMap.put("msg","删除失败");
            }

        } catch (Exception e) {
            LOGGER.error("SupplierController中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return resultMap;
    }

}
